package com.happycolor.littlelove.base;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.apache.http.Header;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.util.EntityUtils;

import android.os.Handler;
import android.os.Message;
import android.widget.Toast;



/**
 * 百度云检索使用类
 * @author Lu.Jian
 *
 */
public class LBSCloudSearch {
	
	private static String mTAG = "NetWorkManager";
	
	//百度云检索API URI
	private static final String SEARCH_URI = "http://api.map.baidu.com/geosearch/poi?";
	
	//云检索公钥
	private static String ak = "F9a1c428f6f419ba5ec4b2d8f2a296fa";
	
	private static String databox_id = "4392";

	private static int TIME_OUT = 12000;
	private static int retry = 3;
	private static boolean IsBusy = false;
	
	/**
	 * 云检索访问
	 * @param filterParams	访问参数，key为filter时特殊处理。
	 * @param handler		数据回调Handler
	 * @param networkType	手机联网类型
	 * @return
	 */
	public static boolean request(final HashMap<String, String> filterParams,final Handler handler, final String networkType) {
		if (IsBusy || filterParams == null)
			return false;
		IsBusy = true;
		
		new Thread() {
			public void run() {
				int count = retry;
				while (count > 0){
					try {
						
						//根据过滤选项拼接请求URL
						String requestURL = SEARCH_URI;
						requestURL = requestURL + "scope=2"  + "&"
										+ "ak=" + ak; 
						
						String filter = null;
						Iterator iter = filterParams.entrySet().iterator();
						while (iter.hasNext()) {
							Map.Entry entry = (Map.Entry) iter.next();
							String key = entry.getKey().toString();
							String value = entry.getValue().toString();
							
							if(key.equals("filter")){
								filter = value;
							}else{
								requestURL = requestURL + "&" + key + "=" + value;
							}
						}
						if(filter != null){
							requestURL = requestURL + "&filter=databox:" + databox_id + filter;
						}else{
							requestURL = requestURL + "&filter=databox:" + databox_id;
						}
						
						HttpGet httpRequest = new HttpGet(requestURL);
						HttpClient httpclient = new DefaultHttpClient();
						httpclient.getParams().setParameter(
								CoreConnectionPNames.CONNECTION_TIMEOUT, TIME_OUT);
						httpclient.getParams().setParameter(
								CoreConnectionPNames.SO_TIMEOUT, TIME_OUT);
						
						HttpProtocolParams.setUseExpectContinue(httpclient.getParams(), false);
						
						if(networkType.equals("cmwap")){
							HttpHost proxy = new HttpHost("10.0.0.172", 80, "http");
							httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,
									proxy);
						}else if(networkType.equals("ctwap")){
							HttpHost proxy = new HttpHost("10.0.0.200", 80, "http");
							httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,
									proxy);
						}


						HttpResponse httpResponse = httpclient.execute(httpRequest);
						int status = httpResponse.getStatusLine().getStatusCode();
						if ( status == HttpStatus.SC_OK ) {
							
							String result = EntityUtils.toString(httpResponse
									.getEntity(), "utf-8");
							Header a = httpResponse.getEntity().getContentType();
							Message msgTmp = handler.obtainMessage(Constant.MSG_NET_SUCC);
							msgTmp.obj = result;
							msgTmp.sendToTarget();
							

							break;
						} else {
							httpRequest.abort();
							Message msgTmp = handler.obtainMessage(Constant.MSG_NET_STATUS_ERROR);
							msgTmp.obj = "HttpStatus error";
							msgTmp.sendToTarget();
						}
					} catch (Exception e) {
						Toast.makeText(LittleLoveApplication.getInstance(), "网络异常，请检查网络后重试！", Toast.LENGTH_SHORT).show();
						e.printStackTrace();
					}
					
					count--;
				}
				
				if ( count <= 0 && handler != null){
					Message msgTmp =  handler.obtainMessage(Constant.MSG_NET_TIMEOUT);
					msgTmp.sendToTarget();
				}
				
				IsBusy = false;
				
			}
		}.start();

		return true;
	}
	
}
